﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace OnWork.Admin.Util.Base
{
    /// <summary>
    /// 模型校验
    /// </summary>
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 方法执行是
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errors = new List<string>();
                foreach (var state in context.ModelState)
                {
                    foreach (var error in state.Value.Errors)
                    {
                        errors.Add(state.Key + ":" + error.ErrorMessage);
                    }
                }
                var errs = new ReturnModel() { Code = (int)HttpStatusCode.BadRequest, Msg = "参数错误", Data = errors };
                context.Result = new ObjectResult(errs);
            }
        }
    }
}